// src/utils/request.js
import axios from "axios";
import { ElMessage } from "element-plus"; // 假设用Element Plus做弹窗；如果不用，替换成alert或你的UI库

const http = axios.create({
  baseURL: "http://dev-cn.your-api-server.com",
  timeout: 5000,
});

// 请求拦截器：加token、通用header
http.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token"); // 假设token存localStorage
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    config.headers["Content-Type"] = "application/json"; // 默认JSON
    return config;
  },
  (error) => {
    console.error("Request Error:", error);
    return Promise.reject(error);
  }
);

// 响应拦截器：处理data、错误弹窗
http.interceptors.response.use(
  (response) => {
    return response.data; // 直接返回data
  },
  (error) => {
    // 网络错误或4xx/5xx
    if (error.response?.status === 401) {
      // token过期，清除并跳转登录
      localStorage.removeItem("token");
      ElMessage.error("登录已过期，请重新登录");
      window.location.href = "/login"; // 替换成你的登录路由
    } else if (error.response?.status === 403) {
      ElMessage.error("无权限访问");
    } else {
      ElMessage.error(error.response?.data?.message || "请求失败");
    }
    return Promise.reject(error);
  }
);

export default http;
